package com.chookss.home.document;


import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;

import com.chookss.MyApp;
import com.chookss.Urls;
import com.johnrambo.ktea.common.klogutil.KLog;
import com.liulishuo.okdownload.DownloadTask;
import com.liulishuo.okdownload.SpeedCalculator;
import com.liulishuo.okdownload.core.breakpoint.BlockInfo;
import com.liulishuo.okdownload.core.breakpoint.BreakpointInfo;
import com.liulishuo.okdownload.core.cause.EndCause;
import com.liulishuo.okdownload.core.listener.DownloadListener4WithSpeed;
import com.liulishuo.okdownload.core.listener.assist.Listener4SpeedAssistExtend;

import java.io.File;
import java.util.List;
import java.util.Map;

public class DownloadService extends Service {
    private DownloadTask task;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(final Intent intent, int flags, int startId) {
        KLog.i("onStartCommand: 下载开始");
        new Thread(new Runnable() {
            @Override
            public void run() {
                String url = intent.getStringExtra("url");
                String fileUrl = intent.getStringExtra("fileUrl");
                String dataCode = intent.getStringExtra("dataCode");
                String fileName = intent.getStringExtra("fileName");
                String tag = intent.getStringExtra("tag");
                int position = intent.getIntExtra("position", 0);
                KLog.i("onStartCommand: " + url);
                KLog.i("onStartCommand: " + fileUrl);
                File file = new File(getFilesDir() + File.separator + Urls.DOWNLOAD);
                if (!file.exists()) {
                    // 按照指定的路径创建文件夹
                    file.mkdirs();
                }
                File SDRootPath3 = new File(getFilesDir() + File.separator + Urls.DOWNLOADCache);
                if (!SDRootPath3.exists()) {
                    // 按照指定的路径创建文件夹
                    SDRootPath3.mkdirs();
                }
                download(fileUrl, url, fileName, dataCode, position, tag);
            }
        }).start();
        return super.onStartCommand(intent, flags, startId);
    }

    private void download(String fileUrl, String url, String fileName, String dataCode, int position, String tag) {

        Intent intent = new Intent();
        intent.setPackage(getPackageName());
        intent.setAction(tag);
        intent.putExtra("dataCode", dataCode);
        intent.putExtra("position", position);
        intent.putExtra("fileUrl", fileUrl);
        intent.putExtra("fileName", fileName);
        intent.putExtra("percent", 1);
        LocalBroadcastManager.getInstance(DownloadService.this).sendBroadcast(intent);
        task = new DownloadTask.Builder(url, new File(getFilesDir() + File.separator + Urls.DOWNLOADCache))
                .setFilename(fileName)
                .setMinIntervalMillisCallbackProcess(500) // 下载进度回调的间隔时间（毫秒）
                .setPassIfAlreadyCompleted(false)// 任务过去已完成是否要重新下载
                .setPriority(10)
                .setPreAllocateLength(false)
                .build();
        task.enqueue(new DownloadListener4WithSpeed() {
            @Override
            public void taskStart(@NonNull DownloadTask task) {
                KLog.i("taskStart: " + task.getId());
            }

            @Override
            public void connectStart(@NonNull DownloadTask task, int blockIndex, @NonNull Map<String, List<String>> requestHeaderFields) {
                KLog.i("connectStart: ");
            }

            @Override
            public void connectEnd(@NonNull DownloadTask task, int blockIndex, int responseCode, @NonNull Map<String, List<String>> responseHeaderFields) {
                KLog.i("connectEnd: ");
            }

            @Override
            public void infoReady(@NonNull DownloadTask task, @NonNull BreakpointInfo info, boolean fromBreakpoint, @NonNull Listener4SpeedAssistExtend.Listener4SpeedModel model) {
                KLog.i("infoReady: ");
            }

            @Override
            public void progressBlock(@NonNull DownloadTask task, int blockIndex, long currentBlockOffset, @NonNull SpeedCalculator blockSpeed) {
                KLog.i("progressBlock: ");
            }

            @Override
            public void progress(@NonNull DownloadTask task, long currentOffset, @NonNull SpeedCalculator taskSpeed) {
                if (task != null) {
                    int percent = (int) (((float) task.getInfo().getTotalOffset() / task.getInfo().getTotalLength()) * 100);
                    KLog.i("progress: " + percent + "%" + "==" + position);
                    if (percent > 1) {
                        intent.putExtra("percent", percent);
                        LocalBroadcastManager.getInstance(DownloadService.this).sendBroadcast(intent);
                    }
                }else{
//                    MyToast.show("下载错误，请稍后重试");
                    stopSelf();
                }
            }

            @Override
            public void blockEnd(@NonNull DownloadTask task, int blockIndex, BlockInfo info, @NonNull SpeedCalculator blockSpeed) {
                KLog.i("blockEnd: ");
            }

            @Override
            public void taskEnd(@NonNull DownloadTask task, @NonNull EndCause cause, @Nullable Exception realCause, @NonNull SpeedCalculator taskSpeed) {
                try {
                    if (task != null) {
                        int percent = (int) (((float) task.getInfo().getTotalOffset() / task.getInfo().getTotalLength()) * 100);
                        if (cause == EndCause.COMPLETED) {
                            intent.putExtra("percent", percent);
                            KLog.i("progress: " + 100 + "%" + "==" + position);
                        }
                        if (realCause != null) {
                            KLog.i(realCause.getMessage());
                            KLog.i(realCause.getCause());
//                            MyToast.show("下载错误，请稍后重试");
                        }
                        LocalBroadcastManager.getInstance(DownloadService.this).sendBroadcast(intent);
                    }
                    stopSelf();
                } catch (Exception e) {
                    e.printStackTrace();
//                    MyToast.show("下载错误，请稍后重试");
                    stopSelf();
                }
            }
        });
        MyApp.downloadTaskHashMap.put(dataCode, task);
    }

}